package com.ch5;

import sun.misc.Unsafe;

import java.lang.reflect.Field;

/**
 * @author woldier
 * @version 1.0
 * @description UnSafe 原子整数累加器 实现
 * @date 2023/5/16 10:30
 **/
public class AtomicInteger {
    /**
     * 原子自增值
     */
    private volatile int value;

    /**
     * value的偏移地址,有了偏移值我们可以计算任意类对象中value的地址,从而获取值
     */
    private final static long valueOffset;
    /**
     * unsafe对象
     */
    private final static Unsafe unsafe;

    static {
        unsafe = UnsafeAccessible.getUnsafe();
        try {
            Field field = AtomicInteger.class.getDeclaredField("value");
            field.setAccessible(true);
            valueOffset = unsafe.objectFieldOffset(field);
        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * description 原子操作
     *
     * @param oldValue 旧值
     * @param newValue 新值
     * @return *
     * @author: woldier
     * @date: 2023/5/16 10:47
     */

    public final boolean inc(int oldValue, int newValue) {
        return unsafe.compareAndSwapInt(this, valueOffset, oldValue, newValue);
    }

    public final int getValue() {
        return value;
    }
}
